package com.frame.servlet;

import com.frame.bean.Img;
import com.frame.service.ImgService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;

@WebServlet(name = "DownloadServlet",urlPatterns = "/download")
public class DownloadServlet extends HttpServlet {
    private static final long servialVersionUID = 1L;
    private ImgService imgService = new ImgService();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String fileId = req.getParameter("fileId");
        Img img = imgService.findImgById(Integer.parseInt(fileId));
        //设置响应头，控制浏览器下载该文件
        resp.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(img.getFilename(), "UTF-8"));
        //读取要下载的文件，保存到文件输入流
        FileInputStream in = new FileInputStream(img.getFilepath());
        //创建输出流
        OutputStream out = resp.getOutputStream();
        //创建缓冲区
        byte buffer[] = new byte[1024*1024*10];
        int len = 0;
        //循环将输入流中的内容读取到缓冲区当中
        while((len=in.read(buffer))>0){
            //输出缓冲区的内容到浏览器，实现文件下载
            out.write(buffer, 0, len);
        }
        //关闭文件输入流
        in.close();
        //关闭输出流
        out.close();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
